<?php

namespace App\Http\Controllers\File;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/10
 * Time: 11:57
 */
use App\Lib\Util\ResponseUtil;
use App\Reagent;
use App\ServiceFiles;
use App\Services\FileService;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\Request;
use Validator;

class FileController extends Controller
{
    private $fileService = null;

    public function __construct(FileService $fileService
    )
    {
        $this->fileService = $fileService;

    }

    /*
     * @author: hy
     * @name: 文件列表
     * @method:GET
     * @param: $request
     * @route:/file/index
     */
    public function fileIndex(Request $request)
    {
        return view('file.fileIndex');
    }

    /*
     * @author: hy
     * @name: 文件列表查询
     * @method:POST
     * @param: $request
     * @route:/file/query
     */
    public function fileQuery(Request $request)
    {
        $input = $request->all();
        return $this->fileService->getFiles($input);
    }


    /*
     * @author: hy
     * @name: 添加&修改文件页面
     * @method:GET
     * @param: $request
     * @route:/file/addIndex
     */
    public function addIndex(Request $request)
    {
        return view('file.fileAddIndex');
    }

    /*
     * @author: hy
     * @name: 上传文件
     * @method:POST
     * @param: $request
     * @route:/file/upload
     */
    public function upload(Request $request)
    {

        $input     = $request->all();
        $file_name = $input['filename'];
        $data      = explode(',', $input['file']);
        $index     = $input['index'];
        $root_path = storage_path() . '/upload/';
        if (!file_exists($root_path)) {
            mkdir($root_path);
        }
        $sub_path = 'document';
        $all_path = $root_path . $sub_path . '/';
        if (!file_exists($all_path)) {
            mkdir($all_path);
        }
        if (!file_put_contents($all_path . $file_name, base64_decode($data[1]))) {
            return ResponseUtil::jsonResponse(false, 1, $file_name . '上传失败!', ['index' => $index]);
        }
        return ResponseUtil::jsonResponse(true, 0, '文件上传成功!', ['file_path' => $sub_path . '/' . $file_name, 'file_name' => $file_name]);
    }

    /*
    * @author: hy
    * @name: 添加文件
    * @method:POST
    * @param: $request
    * @route:/file/add
    */
    public function add(Request $request)
    {
        $input = $request->all();
        $data  = [];
        foreach ($input as $k => $v) {
            $data[$k]['name']    = $v['file_name'];
            $data[$k]['file_id'] = $v['file_path'];
        }
        foreach ($data as $k => $v) {
            $this->addValidate($v);
        }
        $this->fileService->saveFile($data);
        return ResponseUtil::jsonResponse(true, 0, '保存成功!', '');
    }

    public function addValidate($input)
    {
        return Validator::make($input, [
            'name' => [
                'required',
                'unique:service_files,name'
            ],
        ], [
            'name.required' => '文件名必须!',
            'name.unique'   => '该文件已存在!请修改文件名重新上传!',
        ])->validate();
    }

    /*
    * @author: hy
    * @name: 修改文件
    * @method:POST
    * @param: $request
    * @route:/file/edit
    */
    public function edit(Request $request)
    {

    }

    /*
    * @author: hy
    * @name: 删除文件
    * @method:POST
    * @param: $request
    * @route:/file/del
    */
    public function del(Request $request)
    {
        $input = $request->all();
        $this->delValidate($input);
        $this->fileService->delFile($input);
        return ResponseUtil::jsonResponse(true, 0, '删除成功!', '');
    }

    public function delValidate(Array $input)
    {
        return Validator::make($input, [
            'id' => [
                'required'
            ],
        ], [
            'id.required' => 'ID必须',
        ])->after(function ($validator) use ($input) {
            if (!empty($input['id'])) {
                if ($this->fileService->isGoodsFile($input['id']) || $this->fileService->isReagentFile($input['id'])) {
                    $validator->errors()->add('goods.file', '该文件存在其他关联,不可删除!');
                }
            }
        })->validate();
    }


    /*
     * @author: hy
     * @name: 试剂文件管理
     * @method:GET
     * @param: $request
     * @route:/reagent/index
     */
    public function reagentIndex()
    {
        return view('file.reagent');
    }

    /*
     * @author: hy
     * @name: 试剂文件查询
     * @method:POST
     * @param: $request
     * @route:/reagent/query
     */
    public function reagentQuery(Request $request)
    {
        $input = $request->all();
        return $this->fileService->getReagentInfo($input);
    }

    /*
     * @author: hy
     * @name: 试剂文件编辑页面
     * @method:POST
     * @param: $request
     * @route:/reagent/editIndex
     */
    public function reagentEditIndex(Request $request)
    {
        $id          = $request->id;
        $reagentInfo = Reagent::where('id', $id)->first();
        $allFiles    = $this->fileService->getAllFile();
        return view('file.reagentEdit', [
            'all_files'    => $allFiles,
            'reagent_info' => $reagentInfo,
            'id'           => $id
        ]);
    }

    /*
     * @author: hy
     * @name: 试剂文件编辑
     * @method:POST
     * @param: $request
     * @route:/reagent/edit
     */
    public function reagentEdit(Request $reagent)
    {
        $input = $reagent->all();
        $this->fileService->editReagent($input);
        return ResponseUtil::jsonResponse(true, 0, '修改成功!', '');
    }

    //获取excel文件内容
    public function testExcel(Request $request)
    {
        $file = $request->file('excelUp');
        if(ServiceFiles::$MIME_TYPE[$file->getClientMimeType()] != 'xls'){
            return ResponseUtil::jsonResponse(false, 1, '文件类型错误!', '');
        }
        $fileName = date('Y-m-d').'-'.uniqid().'.xls';
        //dd($fileName);
        // 增加判断 当上传文件夹不存在时创建文件夹,避免服务器 报错 500;
        if(!file_exists(storage_path('app/exportexcel'))){
            mkdir(storage_path('app/exportexcel'));
        }
        file_put_contents(storage_path('app/exportexcel').'/'.$fileName,file_get_contents($file->getRealPath()));
        return ResponseUtil::jsonResponse(true, 0, '上传成功', ['file_name'=>$fileName,'old_name'=>$file->getClientOriginalName()]);

       /* Excel::load($filePath, function($reader) {
            $data = $reader->ignoreEmpty()->takeColumns(5)->get();
//            dd($data);
            foreach($data as $k=>$v){

            }
        });*/
    }
}
